package com.lp.multi.juc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: lp
 * @create: 2021-06-26 21:09
 * @description: 精确唤醒锁
 * 非静态方法，同一个锁(同一个资源),加锁代码块拥有独立的监视器
 * A线程执行完成-->B线程执行完成-->C线程执行完成
 */
public class PrecisionLock {
    public static void main(String[] args) {
        MultiThreadResource multiThreadResource = new MultiThreadResource();
        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(1);
                multiThreadResource.methodA();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"A").start();
        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(1);
                multiThreadResource.methodB();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"B").start();
        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(1);
                multiThreadResource.methodC();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"C").start();


    }
}


class MultiThreadResource{
    //0-调用A；1-调用B；2-调用C
    private Integer number=0;
    private Lock lock = new ReentrantLock();
    private Condition conditionA = lock.newCondition();
    private Condition conditionB = lock.newCondition();
    private Condition conditionC = lock.newCondition();

    public void methodA() throws InterruptedException {
        lock.lock();
        try {
            while (number !=0){
                conditionA.await();
            }
            System.out.println(Thread.currentThread().getName()+" run methodA");
            number ++;
            conditionB.signal();
        }finally {
            lock.unlock();
        }

    }
    public void methodB() throws InterruptedException {
        lock.lock();
        try {
            while (number !=1){
                conditionB.await();
            }
            System.out.println(Thread.currentThread().getName()+" run methodB");
            number ++;
            conditionC.signal();
        }finally {
            lock.unlock();
        }
    }
    public void methodC() throws InterruptedException {
        lock.lock();
        try {
            while (number !=2){
                conditionC.await();
            }
            System.out.println(Thread.currentThread().getName()+" run methodC");
            number = 0;
            conditionA.signal();
        }finally {
            lock.unlock();
        }
    }

}
